import Cesium from '../Ces/Cesium'
import GeojsonVtTileIndex from '../Module/VectorTile/GeojsonVtTileIndex'
import OlVtImageryRender from '../Module/VectorTile/OlVtImageryRender'
import Style from 'ol/style/Style'
import Fill from 'ol/style/Fill'

let defaultStyle
const getFeatureStyle = function () {
  if (!defaultStyle) {
    defaultStyle = new Style({
      fill: new Fill({
        color: '#f00',
      }),
    })
  }

  return defaultStyle
}

class WeImageryLayerFilterProvider {
  olRender: OlVtImageryRender
  ready: boolean = false
  debug: boolean = false
  private _url: any
  private _readyPromise = Cesium.defer()
  constructor(options) {
    this.debug = Boolean(options.debug)
    this._url = options.url
  }

  load() {
    const url = this._url
    const promise = url.fetchJson ?
      url.fetchJson() : Cesium.Resource.fetchJson(url)
    promise.then((json) => {
      const tileIndex = new GeojsonVtTileIndex(json, true)
      this.olRender = new OlVtImageryRender({ tileIndex, styleFunc: getFeatureStyle })
      this._readyPromise.resolve(true)
    }).catch(() => {
      this._readyPromise.resolve(false)
    })
    return this._readyPromise.promise
  }

  requestImage(x, y, level, provider) {
    if (this.debug) {
      const canvas = document.createElement("canvas")
      canvas.width = provider.tileWidth
      canvas.height = provider.tileHeight
      const context = canvas.getContext("2d")

      const cssColor = Cesium.Color.RED.toCssColorString()

      context.strokeStyle = cssColor
      context.lineWidth = 2
      context.strokeRect(1, 1, 511, 511)

      context.font = "bold 25px Arial"
      context.textAlign = "center"
      context.fillStyle = cssColor
      context.fillText(`L: ${level}`, 124 * 2, 86 * 2)
      context.fillText(`X: ${x}`, 124 * 2, 136 * 2)
      context.fillText(`Y: ${y}`, 124 * 2, 186 * 2)

      return Promise.resolve(canvas)
    }

    if (!this.olRender) {
      return null
    }

    return this.olRender.requestImage(x, y, level, null, provider)
  }
}

export default WeImageryLayerFilterProvider
